package com.dd.probe.common.util.page;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author liuxianmeng
 * @CreateTime 2024/11/5 1:49
 * @Description VO分页信息 返回给前端的
 */
@Data
@NoArgsConstructor
@ApiModel("分页信息类")
public class PageInfoVO<T> {
    @ApiModelProperty("当前页码")
    private long pageNum;
    @ApiModelProperty("每页记录数")
    private long pageSize;
    @ApiModelProperty("起始行号")
    private long startRow;
    @ApiModelProperty("结束行号")
    private long endRow;
    @ApiModelProperty("总记录数")
    private long totalRows;
    @ApiModelProperty("总页数")
    private long totalPages;
    @ApiModelProperty("上一页")
    private long prePage;
    @ApiModelProperty("下一页")
    private long nextPage;
    @ApiModelProperty("是否是第一页")
    private boolean isFirstPage;
    @ApiModelProperty("是否是第一页")
    private boolean isLastPage;
    @ApiModelProperty("是否有上一页")
    private boolean hasPreviousPage;
    @ApiModelProperty("是否有下一页")
    private boolean hasNextPage;
    @ApiModelProperty("当前页所有数据")
    private List<T> list;

    public PageInfoVO(CurPage<T> curPage) {
        if (curPage == null) {
            throw new IllegalArgumentException("CurPage must not be null");
        }

        this.pageNum = curPage.getPageNum();
        this.pageSize = curPage.getPageSize();
        this.totalRows = curPage.getTotalRows();
        this.list = curPage.getList() != null ? new ArrayList<>(curPage.getList()) : Collections.emptyList();

        calculatePageInfo();
    }

    private void calculatePageInfo() {
        this.startRow = (this.pageNum - 1) * this.pageSize + 1;
        /**
         * 严谨
         */
        this.endRow = Math.min(this.startRow + this.pageSize - 1, this.totalRows);
        this.totalPages = (int) Math.ceil(this.totalRows * 1.0 / this.pageSize);
        this.prePage = this.pageNum - 1;
        this.nextPage = this.pageNum + 1;
        this.isFirstPage = this.pageNum == 1;
        this.isLastPage = this.nextPage > this.totalPages;
        this.hasPreviousPage = this.pageNum > 1;
        this.hasNextPage = this.nextPage <= this.totalPages;
    }
}
